package com.game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Random;

public class GamePanel extends JFrame {
    //定义窗口尺寸
    int width = 1260;
    int height = 800;
    //定义双缓存图片
    Image offScreemImage = null;
    //定义指针图片
    Image select = Toolkit.getDefaultToolkit().getImage("image/cxkboom.gif");
    //指针的初值纵坐标（通过纵坐标的改变来改变图片位置）
    int initY = 330;
    //游戏模式：0 游戏未开始，1 单人模式，2 双人模式，3 游戏失败，4 游戏胜利，5 暂停
    int satte = 0;
    //中间变量，回车时给satte 赋a的值
    int a = 1;
    //定义重绘次数
    int count = 0;
    //定义已生成敌人数量
    int enemyCount = 0;

    //定义PlayerOne——我方坦克
    PlayerOne playerOne = new PlayerOne("image/cxk.gif",450,735,this,"image/player1/p1tankU.gif",
            "image/player1/p1tankL.gif","image/player1/p1tankR.gif","image/player1/p1tankD.gif");
    //定义PlayerTwo
    PlayerTwo playerTwo = new PlayerTwo("image/cxk.gif",720,735,this,"image/player2/p2tankU.gif",
            "image/player2/p2tankL.gif","image/player2/p2tankR.gif","image/player2/p2tankD.gif");

    //游戏元素列表
    //我方子弹集合
    ArrayList<Bullet> bulletList = new ArrayList<Bullet>();
    //敌方子弹集合
    ArrayList<EnemyBullet> enemyBulletsList = new ArrayList<EnemyBullet>();
    //存储删除子弹
    ArrayList<Bullet> removeList = new ArrayList<>();
    ArrayList<EnemyBullet> removeList2 = new ArrayList<>();
    //敌方坦克集合
    ArrayList<Bot> botlist = new ArrayList<Bot>();
    //玩家列表
    ArrayList<Tank> playerList = new ArrayList<Tank>();
    //围墙列表
    ArrayList<Wall> wallList = new ArrayList<Wall>();
    //铁墙列表
    ArrayList<Fe> feList = new ArrayList<Fe>();
    //草从列表
    ArrayList<Grass> grassList = new ArrayList<Grass>();
    //基地列表
    ArrayList<Base> baseList = new ArrayList<Base>();
    //爆炸图列表
    ArrayList<Explode> explodeList = new ArrayList<Explode>();

    /*
    * 随机生成围墙
    * */
    ///随机生成的墙体数量
    private int wallCount=100;
    private boolean d=true;
    private int[]xrr=new int[wallCount];
    private int[]yrr=new int[wallCount];
    public void random() {
        Random r = new Random();
        for (int i = 0; i < wallCount; ) {
            int x = r.nextInt(20);
            int y = r.nextInt(8) + 3;
            if (i > 0) {
                boolean repeat = false;
                for (int j = 0; j < i; j++) {
                    if (xrr[j] == x * 60 && yrr[j] == y * 60) {
                        repeat = true;
                    }
                }
                if (!repeat) {
                    xrr[i] = x * 60;
                    yrr[i] = y * 60;
                    i++;
                } else {
                    continue;
                }
            } else {
                xrr[i] = x * 60;
                yrr[i] = y * 60;
                i++;
            }
        }
    }
    public void add() {
        random();
        //添加围墙
        for(int i=0;i<21;i++) {
            wallList.add(new Wall("image/walls.gif",i*60,120,this));
        }
        wallList.add(new Wall("image/walls.gif",520,740,this));
        wallList.add(new Wall("image/walls.gif",520,680,this));
        wallList.add(new Wall("image/walls.gif",580,680,this));
        wallList.add(new Wall("image/walls.gif",640,680,this));
        wallList.add(new Wall("image/walls.gif",640,740,this));
        for (int i = 0; i < wallCount; i++) {
            Random a = new Random();
            int num = a.nextInt(4);
            if (num < 2) {
                Wall wall = new Wall("image/walls.gif", xrr[i], yrr[i], null);
                wallList.add(wall);
            } else if (num < 3) {
                Grass g = new Grass("image/cao.gif", xrr[i], yrr[i], null);
                grassList.add(g);
            } else {
                Fe f = new Fe("image/fe.gif", xrr[i], yrr[i], null);
                feList.add(f);
            }
        }
    }

    /*
    * 窗口的启动方法
    * */
    public void launch() {
        setTitle("IKUN坦克大战");
        setSize(width, height);
        //设置屏幕居中
        setLocationRelativeTo(null);
        //关闭时退出 3
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //用户不能调整大小
        setResizable(false);
        setVisible(true);
        //给窗口添加键盘监视器
        this.addKeyListener(new GamePanel.KeyMonitor());
        //绘制围墙
        add();
        //绘制基地
        baseList.add(new Base("image/bullet/卡通1.png", 580, 740, this));

        /*
         * 重绘 控制屏幕刷新时间
         * */
        while (true) {
            //每重绘一百次 添加一辆敌方坦克
            if (count % 100 == 1 && enemyCount < 10 && (satte == 1 || satte == 2)) {
                boolean a = true;
                Random random = new Random();
                int rnum = random.nextInt(19) + 1;
                if (enemyCount > 0) {
                    for (Bot b : botlist) {
                        if (Math.abs(rnum * 50 - b.getX()) < 120) {//不让重叠
                            a = false;
                        }
                    }
                    if (a) {
                        botlist.add(new Bot("image/enemy/enemy1D.gif", rnum * 50, 60, this, "image/enemy/enemy1U.gif",
                                "image/enemy/enemy1L.gif", "image/enemy/enemy1R.gif", "image/enemy/enemy1D.gif"));
                        enemyCount++;
                    }
                } else {
                    botlist.add(new Bot("image/enemy/enemy1D.gif", rnum * 50, 60, this, "image/enemy/enemy1U.gif",
                            "image/enemy/enemy1L.gif", "image/enemy/enemy1R.gif", "image/enemy/enemy1D.gif"));
                    enemyCount++;
                }
            }
            //爆炸集合不为空，则删除集合中第一个元素
            //多开一个线程让爆炸动画播放1秒后消失
            new Thread(() -> {
                if (!explodeList.isEmpty()) {
            try {
                Thread.sleep(1500);
                int size = explodeList.size();
                if (size != 0){
                    explodeList.remove(0);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
            }).start();

            //游戏胜利条件
            if (botlist.size() == 0 && enemyCount == 10) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        satte = 4;
                    }
                }).start();

            }
            //游戏失败条件
            if ((playerList.size() == 0 && (satte == 1 || satte == 2)) || baseList.size() == 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        satte = 3;
                    }
                }).start();

            }
            repaint();
            try {
                Thread.sleep(25);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /*
    * 重写paint方法
    * */
    @Override
    public void paint(Graphics g) {
        //System.out.println(bulletList.size());
        //System.out.println(removeList.size());
        //创建和窗口一样大小的Image图片
        if (offScreemImage == null){
            offScreemImage = this.createImage(width,height);
        }
        //获取该Image图片的画笔
        Graphics gImage = offScreemImage.getGraphics();
        //设置画笔颜色
        gImage.setColor(Color.black);
        //绘制实心矩形填充整个画布
        gImage.fillRect(0,0,width,height);
        gImage.setColor(Color.pink);
        //改变文字大小和样式
        gImage.setFont(new Font("宋体",Font.BOLD,50));

        //satte=0,游戏未开始
        if (satte == 0){
            //添加文字
            gImage.drawString("请选择游戏模式",440,290);
            gImage.drawString("单人模式",510,400);
            gImage.drawString("双人模式",510,500);
            gImage.drawString("按1,2键选择 回车确认 P暂停游戏",240,650);
            gImage.setColor(Color.ORANGE);
            gImage.setFont(new Font("宋体",Font.BOLD,100));
            gImage.drawString("IKUN坦克大战",320,180);
            //绘制指针
            gImage.drawImage(select,390,initY,100,100,null);
        }
        else if (satte == 1 || satte == 2){
            gImage.setFont(new Font("宋体",Font.BOLD,20));
            //显示敌人数量
            gImage.drawString("剩余敌人：" + botlist.size(),10,55);
            gImage.setFont(new Font("宋体",Font.PLAIN,15));
            if (satte == 1){
                gImage.drawString("单人模式",10,780);
            }
            else {
                gImage.drawString("双人模式",10,780);
            }

            //绘制游戏元素
            //绘制PlayerOne元素
            for (Tank player : playerList) {
                player.paintSelf(gImage);
            }
            //遍历绘制子弹
            for (Bullet bullet : bulletList) {
                bullet.paintSelf(gImage);
            }
            //遍历完子弹后删除removeList里面需要删除的子弹
            bulletList.removeAll(removeList);
            for (EnemyBullet enemyBullet : enemyBulletsList) {
                enemyBullet.paintSelf(gImage);
            }
            enemyBulletsList.removeAll(removeList2);
            //绘制Bot元素
            for (Bot bot : botlist) {
                bot.paintSelf(gImage);
            }
            //绘制围墙
            for (Wall wall : wallList) {
                wall.paintSelf(gImage);
            }
            for (Grass grass : grassList) {
                grass.paintSelf(gImage);
            }
            for (Fe fe : feList) {
                fe.paintSelf(gImage);
            }
            //绘制基地
            for (Base base : baseList) {
                base.paintSelf(gImage);
            }
            //绘制爆炸图
            for (Explode explode : explodeList) {
                explode.paintSelf(gImage);
            }

        }
        else if (satte == 3) {
            //gImage.drawString("游戏失败！",510,400);
            gImage.drawImage(Toolkit.getDefaultToolkit().getImage("E:\\JAVA IDEA\\各种小项目\\坦克大战\\tankwar\\image\\shibai.png"), 315, 200, this);
        }
        else if (satte == 4){
            Music.gameSucceedPlay();
            gImage.drawString("游戏胜利！",510,120);
            gImage.drawImage(Toolkit.getDefaultToolkit().getImage("E:\\JAVA IDEA\\各种小项目\\坦克大战\\tankwar\\image\\loli.gif"), 320, 150,600,600,this);
        }
        else if (satte == 5) {
            gImage.drawString("游戏暂停",510,400);
        }
        //将绘制好的图片一次性绘制到画布中
        g.drawImage(offScreemImage,0,0,null);
        //重绘一次
        count++;
    }

    /*
    * 键盘监听事件（继承或含有JFrame类）
    * */
    class KeyMonitor extends KeyAdapter{
        //按下键盘
        @Override
        public void keyPressed(KeyEvent e) {
            //返回键值
            int key = e.getKeyCode();
            switch (key) {
                case KeyEvent.VK_NUMPAD1:
                    a = 1;
                    initY = 330;
                    break;
                case KeyEvent.VK_NUMPAD2:
                    a = 2;
                    initY = 440;
                    break;
                case KeyEvent.VK_ENTER:
                    Music.startPlay();
                    satte = a;
                    //playerOne
                    playerList.add(playerOne);
                    //playerOne状态改为存活
                    playerOne.alive = true;
                    //playerTwo
                    if (satte == 2){
                        //如果是输入模式 加入playerTwo
                        playerList.add(playerTwo);
                        //playerTwo状态改为存活
                        playerTwo.alive = true;
                    }
                    break;
                case KeyEvent.VK_P:
                    //解决主界面也可以暂停的bug
                    if (satte == 1 || satte == 2 || satte == 5){
                        //实现游戏暂停 开始
                        if (satte != 5 ){
                            a = satte;
                            satte = 5;
                        }
                        else {
                            satte = a;
                        }
                    }
                default:
                    //玩家一的键盘事件
                    playerOne.keyPressed(e);
                    //玩家二的键盘事件
                    playerTwo.keyPressed(e);
            }
        }
        //松开键盘
        @Override
        public void keyReleased(KeyEvent e){
            //玩家一的键盘事件
            playerOne.keyReleased(e);
            //玩家二的键盘事件
            playerTwo.keyReleased(e);
        }
    }


    public static void main(String[] args) {
        GamePanel gamePanel = new GamePanel();
        gamePanel.launch();
    }
}
